﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsolePro.Practice
{
    public class SocketPractice
    {

        public static void ServicePoint()
        {
            int port = 6767;
            var ip = IPAddress.Any;
            var receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            receiveSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);   
            var endPoint = new IPEndPoint(ip, port);
            receiveSocket.Bind(endPoint); //绑定IP地址和端口号
            receiveSocket.Listen(10);

            Console.WriteLine("开始监听Accpet");
            while (true)
            {
                // 接收到得到对应客户端的套接管道
                var socket = receiveSocket.Accept();
                
                Task.Run(() => ToServer(socket));
            }


        }

        public static void ToServer(Socket socket)
        {
            var buffer = new byte[1024];
            socket.Receive(buffer);
            Console.WriteLine($"接收到消息：" + Encoding.UTF8.GetString(buffer));
            var send = Encoding.UTF8.GetBytes("我已经收到你的信息了");
            socket.Send(send);
            send = Encoding.UTF8.GetBytes("1636我已经收到你的信息了");
            socket.Send(send);
            send = Encoding.UTF8.GetBytes("13613我已经收到你的信息了");
            socket.Send(send);
            send = Encoding.UTF8.GetBytes("1461346我已经收到你的信息了");
            socket.Send(send);
            send = Encoding.UTF8.GetBytes("22");

            socket.Send(send);
            Console.WriteLine("*** 已回复信息给客户端");


            var count = 0;
            while (true)
            {
                buffer = new byte[1024];
                socket.Receive(buffer);
                Console.WriteLine($"接收到客户端返回消息：" + buffer[0]);
                count++;
                if (count > 60) break;
            }

        }

        public static void Client()
        {
            string IP = "127.0.0.1";
            int port = 6767;
            var ip = IPAddress.Parse(IP);  //将IP地址字符串转换成IPAddress实例
            var ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
            var endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
            ClientSocket.Connect(endPoint);  //与远程主机建立连接

            Console.WriteLine("开始发送消息");
            var message = Encoding.UTF8.GetBytes("我是Hans请求连接到服务器");  //通信时实际发送的是字节数组，所以要将发送消息转换字节
            ClientSocket.Send(message);
            Console.WriteLine("** 已发送消息");
            var count = 0;
            var allByte = new List<byte>();
            ClientSocket.Blocking = false;

            while (true)
            {
                var receive = new byte[3];
                Thread.Sleep(200);

                ClientSocket.BeginReceive(receive, 0, receive.Length, SocketFlags.None, new AsyncCallback((ar) => {
                    // 如果有读取到数据时，执行的回调
                    try
                    {
                        allByte.AddRange(receive);
                    }
                    catch (ObjectDisposedException)
                    { }
                    catch (Exception ex)
                    {
                        Console.WriteLine("错误：" + ex.Message);
                    }
                }), null);

                Console.WriteLine($"接收次数{count}");

                if (count > 50) break;
                count++;
            }

            Console.WriteLine($"接收总消息为：" + Encoding.UTF8.GetString(allByte.ToArray()));
            Console.WriteLine("** 断开与服务器的连接");
            ClientSocket.Close();  //关闭连接
        }

    }
}
